/*
 * Copyright 2022 Netflix, Inc.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package cn.orangeframe.neon.application.tasks;

import cn.orangeframe.neon.application.run.WorkflowExecutor;
import cn.orangeframe.neon.domain.entity.WorkflowTask;
import cn.orangeframe.neon.domain.model.TaskModel;
import cn.orangeframe.neon.domain.model.WorkflowModel;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 任务执行器
 */
@Getter
public abstract class WorkflowSystemTask {

    private final String taskType;

    private static final Map<String, WorkflowSystemTask> registry = new HashMap<>();

    public WorkflowSystemTask(String name) {
        registry.put(name, this);
        this.taskType = name;
    }

    public static WorkflowSystemTask get(String type) {
        return registry.get(type);
    }

    public void execute(WorkflowModel workflow, TaskModel task, WorkflowExecutor executor) {
    }

    /**
     * @return True to keep task in 'IN_PROGRESS' state, and 'COMPLETE' later by an external
     *     message.
     */
    public boolean isAsyncComplete(TaskModel task) {
        if (task.getInputData().containsKey("asyncComplete")) {
            return Optional.ofNullable(task.getInputData().get("asyncComplete"))
                    .map(result -> (Boolean) result)
                    .orElse(false);
        } else {
            return Optional.ofNullable(task.getWorkflowTask())
                    .map(WorkflowTask::getAsyncComplete)
                    .orElse(false);
        }
    }
}
